package cn.tedu.ximart.server.service.impl;


import cn.tedu.ximart.server.constant.CommonConst;
import cn.tedu.ximart.server.ex.ServiceException;

import cn.tedu.ximart.server.mapper.AlbumMapper;
import cn.tedu.ximart.server.mapper.PictureMapper;
import cn.tedu.ximart.server.pojo.dto.AlbumAddNewDTO;
import cn.tedu.ximart.server.pojo.dto.AlbumUpdateDTO;
import cn.tedu.ximart.server.pojo.entity.Album;
import cn.tedu.ximart.server.pojo.vo.AlbumDetailVO;
import cn.tedu.ximart.server.pojo.vo.AlbumListItemVO;
import cn.tedu.ximart.server.service.IAlbumService;
import cn.tedu.ximart.server.web.JsonPage;
import cn.tedu.ximart.server.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AlbumServiceImpl implements IAlbumService {

    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private PictureMapper pictureMapper;

    public AlbumServiceImpl() {
        System.out.println("AlbumServiceImpl的构造方法被调用了");
    }

    @Override
    public Long addNew(AlbumAddNewDTO albumAddNewDTO) {
        log.debug("开始处理增加相册的业务，参数：{}", albumAddNewDTO);
        //检查名称是否已存在
        String name = albumAddNewDTO.getName();
        int count = albumMapper.countByName(name);
        if (count > 0) {
            String message = "增加相册失败，相册名称【" + name + "】已经被占用";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        //执行插入相册
        Album album = new Album();
        BeanUtils.copyProperties(albumAddNewDTO, album);
        album.setSort(albumAddNewDTO.getSort() == null ? CommonConst.SORT_DEFAULT : albumAddNewDTO.getSort());
        log.debug("即将向数据库中写入数据：{}", album);
        int rows = albumMapper.insert(album);
        if (rows != 1) {
            String message = "添加分类失败，服务器繁忙，请稍后再尝试";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        return album.getId();
    }

    @Override
    public void deleteById(Long id) {
        //检查准备删除的相册是否存在
        AlbumDetailVO album = albumMapper.selectByPrimaryKey(id);
        if (album == null) {
            String message = "删除相册失败,该相册不存在";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        //检查该相册下是否包含图片
        int count = pictureMapper.countByAlbumId(id);
        if (count > 0) {
            String message = "删除相册失败,该相册内还有图片";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        //执行删除
        log.debug("删除id为{}的相册数据", id);
        int rows = albumMapper.deleteByPrimaryKey(id);
        if (rows != 1) {
            String message = "删除分类失败，找不到id为" + id + "的数据";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
    }

    @Override
    public void deleteByIds(Long... ids) {
        int rows = albumMapper.deleteByIds(ids);
        log.info("批量删除{}条数据", rows);
    }

    @Override
    public void updateById(Long id, AlbumUpdateDTO albumUpdateDTO) {
        log.debug("开始更新相册, id={}, 新数据={}", id, albumUpdateDTO);
        //检查尝试更新相册是否存在
        {
            AlbumDetailVO album = albumMapper.selectByPrimaryKey(id);
            if (album == null) {
                String message = "更新相册失败,尝试修改的相册不存在!";
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            }
        }
        //检查新名字是否冲突
        String albumNewName = albumUpdateDTO.getName();
        AlbumDetailVO checkName = albumMapper.getByName(albumNewName);
        if (checkName != null && !checkName.getId().equals(id)) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,
                    "更新相册信息失败,相册名称(" + albumNewName +")已存在");
        }

        // 执行更新
        Album album = new Album();
        BeanUtils.copyProperties(albumUpdateDTO, album);
        album.setId(id);
        album.setName(albumUpdateDTO.getName());
        album.setDescription(albumUpdateDTO.getDescription());
        album.setSort(albumUpdateDTO.getSort() == null ? CommonConst.SORT_DEFAULT : albumUpdateDTO.getSort());
        log.debug("即将提交更新相册数据：{}", album);
        int rows = albumMapper.updateSelective(album);
        if (rows != 1) {
            throw new ServiceException(ServiceCode.ERR_UPDATE, "更新相册信息失败，服务器忙，请稍后再次尝试！");
        }
    }

    @Override
    public AlbumDetailVO getById(Long id) {
        AlbumDetailVO albumDetailVO = albumMapper.getById(id);
        if (albumDetailVO==null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"获取相册详情失败,尝试访问数据不存在");
        }
        return albumDetailVO;
    }

    @Override
    public JsonPage<AlbumListItemVO> list(Integer page, Integer pageSize) {
        log.debug("查询相册列表,页码={},每页条数={}",page,pageSize);
        PageHelper.startPage(page,pageSize);
        List<AlbumListItemVO> albums = albumMapper.list();
        log.debug("查询分页相册列表: page={},size={}",page,pageSize);
        return JsonPage.restPage(new PageInfo<>(albums));
    }

    @Override
    public List<AlbumListItemVO> list() {
        log.debug("开始处理查询相册列表的业务");
        return albumMapper.list();
    }

}
